package com.imay.live.activity.recharge;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.adapter.BuyLinearAdapter;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.BuyMViewModel;
import com.imay.live.view.custom.LoadEmptyViewControl;
import com.imay.live.view.custom.RechargeTitle;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.tbas_api.IMYTBASObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static com.imay.live.proto.ResultCode.CodeAccountMeiliNotEnough;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by lzx on 2017/04/17 0017.
 * 魅力购买 兑换(魅力->魅钻)
 */

public class BuyDiamondsActivity extends BaseRequestActivity {
    private RecyclerView mrecyclerView;
    BuyLinearAdapter mAdapter;
    ArrayList<MultiItemEntity> mdatas;
    boolean isloading;
    FrameLayout frame_layout;
    LoadEmptyViewControl loadEmptyViewControl;
    long maxmeili;
    IMYTBASObject mSocketNotify;
    RechargeTitle rechargeTitle;

    public static void start(Context context) {
        Intent starter = new Intent(context, BuyDiamondsActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_buydiamond;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.recharge_mbuy));
        mrecyclerView = $(R.id.rcv_charge);
        frame_layout = $(R.id.frame_layout);
        mdatas = new ArrayList<MultiItemEntity>();
        WrapContentLinearLayoutManager wrapContentLinearLayoutManager
                = new WrapContentLinearLayoutManager(this);
        mrecyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        mAdapter = new BuyLinearAdapter(mdatas);
        mAdapter.bindToRecyclerView(mrecyclerView);
        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (isloading) {
                    return;
                }
                ArrayList<MultiItemEntity> datas = (ArrayList<MultiItemEntity>) adapter.getData();
                final BuyMViewModel buyMViewModel = (BuyMViewModel) datas.get(position);
                UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
                if (userInfoModel != null) {
                    UserInfoModel.MoneyModel moneyModel = userInfoModel.getMoney();
                    if (moneyModel != null) {
                        maxmeili = moneyModel.getMeili();
                    }
                }
                if (maxmeili > buyMViewModel.getMeili()) {
                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getResources().getString(R.string.exchangeshow), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            exchangeLoad(buyMViewModel.getMeili());
                        }
                    });
                } else {
//                    ToastUtil.show(BuyDiamondsActivity.this, getResources().getString(R.string.profitlast_last));
                }
            }
        });
        loadEmptyViewControl = new LoadEmptyViewControl(BuyDiamondsActivity.this);
        loadEmptyViewControl.addLoadView(frame_layout);
        exchangeListLoad();
        registerSocketNotify();
    }

    //充值变化
    private void registerSocketNotify() {
        //监听socket
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = EventHelper.EVENT_SOCK_NOTIFY;
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
//                {"content":"{\"uid\":4179,\"diamond\":9999999978917,\"meili\":3682,\"meiliGain\":3832}","msg_id":341,"seq":0}
                if (object.socket_msg_id == MessageId.userMoneyUpdateNotify) {
                    try {
                        JSONObject jsonObject = new JSONObject(object.socket_content);
                        final int meili = jsonObject.getInt("meili");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (rechargeTitle != null) {
                                    rechargeTitle.setText(meili);
                                    UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
                                    if (userInfoModel != null) {
                                        UserInfoModel.MoneyModel moneyModel = userInfoModel.getMoney();
                                        if (moneyModel != null) {
                                            moneyModel.setMeili(meili);
                                            UserInfoCache.saveUserInfo(userInfoModel);
                                            for (MultiItemEntity multiItemEntity : mAdapter.getData()) {
                                                if (multiItemEntity instanceof BuyMViewModel) {
                                                    BuyMViewModel buyM = (BuyMViewModel) multiItemEntity;
                                                    buyM.setChecked(buyM.getMeili() <= meili);
                                                }
                                            }
                                            mAdapter.notifyDataSetChanged();
                                        }
                                    }
                                }

                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    private void exchangeListLoad() {
        ProtoRequestHelper.task(ProtoHttpFactory.getexchangeList()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {

                Result<ArrayList<BuyMViewModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<BuyMViewModel>>>() {
                }.getType());
                if (result.result == CodeSuccess) {
                    rechargeTitle = new RechargeTitle(BuyDiamondsActivity.this);
                    UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
                    rechargeTitle.setText(0);
                    rechargeTitle.setTitleText(getResources().getString(R.string.profitlast));
                    if (userInfoModel != null) {
                        UserInfoModel.MoneyModel moneyModel = userInfoModel.getMoney();
                        if (moneyModel != null) {
                            maxmeili = moneyModel.getMeili();
                            rechargeTitle.setText(maxmeili);
                        }
                    }
                    mAdapter.addHeaderView(rechargeTitle);
                    for (MultiItemEntity multiItemEntity : result.data) {
                        if (multiItemEntity instanceof BuyMViewModel) {
                            BuyMViewModel buyM = (BuyMViewModel) multiItemEntity;
                            buyM.setChecked(buyM.getMeili() <= maxmeili);
                        }
                    }
                    mrecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            mrecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            if ((frame_layout.getHeight() - mrecyclerView.getHeight()) > 0) {
                                final View aview = new View(BuyDiamondsActivity.this);
                                FrameLayout.LayoutParams paramse = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (frame_layout.getHeight() - mrecyclerView.getHeight()));
                                aview.setLayoutParams(paramse);
                                paramse.gravity = Gravity.BOTTOM;
                                aview.setBackgroundColor(Color.WHITE);
                                frame_layout.addView(aview,0);
                            }


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadEmptyViewControl.loadcomplete();
                                    frame_layout.setBackgroundColor(Color.TRANSPARENT);
                                }
                            });

                        }
                    });
                    mdatas.addAll(result.data);
                    mAdapter.notifyDataSetChanged();


                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadEmptyViewControl.loadError(message);
            }
        });
    }

    private void exchangeLoad(int meili) {
        isloading = true;
        ProtoRequestHelper.task(ProtoHttpFactory.postexchange(meili)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                isloading = false;
                Result<String> result = JSON.parseObject(data, new TypeReference<Result<String>>() {
                }.getType());
                if (result.result == CodeSuccess) {
                    ToastUtil.show(BuyDiamondsActivity.this, getResources().getString(R.string.exchangesuccess));
                } else if (result.result == CodeAccountMeiliNotEnough) {
                    ToastUtil.show(BuyDiamondsActivity.this, getResources().getString(R.string.exchangeempty));
                } else {
                    ToastUtil.show(BuyDiamondsActivity.this, getResources().getString(R.string.exchangefail));
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                isloading = false;
                ToastUtil.show(BuyDiamondsActivity.this, getResources().getString(R.string.exchangefail));
            }
        });
    }
}
